package com.eclink.asset.consume.handler;


import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.alibaba.fastjson.JSON;
import com.eclink.asset.asset.domain.dao.FlowApply;
import com.eclink.asset.consume.domain.dao.ConsumeInventoryBatch;
import com.eclink.asset.consume.domain.form.ApplyFormDataHCRK;
import com.eclink.asset.consume.mapper.ConsumeInventoryBatchMapper;
import com.eclink.asset.enums.ApplyStateEnum;
import com.eclink.asset.workflow.mapper.FlowApplyMapper;
import com.eclink.asset.workflow.handler.ApplyFinishHandler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class ConsumeApplyInHandler implements ApplyFinishHandler {

    @Resource
    private FlowApplyMapper flowApplyMapper;

    @Resource
    private ConsumeInventoryBatchMapper consumeInventoryBatchMapper;


    @Resource
    private SnowflakeGenerator snowflakeGenerator;

    private void saveItem(ConsumeInventoryBatch item, Long warehouseId, String applyNumber) {

        String batchNumber = snowflakeGenerator.next() + "";
        item.setApplyNumber(applyNumber);
        item.setWarehouseId(warehouseId);
        item.setBatchNumber(batchNumber);
        item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getNum())));
        consumeInventoryBatchMapper.insert(item);
    }

    @Transactional
    public void execute(String id) {

        FlowApply flowApply = flowApplyMapper.selectById(id);
        String applyNumber = flowApply.getNumber();
        flowApply.setUpdateTime(LocalDateTime.now());
        flowApply.setState(ApplyStateEnum.APPROVED.getValue());
        flowApplyMapper.updateById(flowApply);

        ApplyFormDataHCRK formData = JSON.parseObject(flowApply.getFormData(), ApplyFormDataHCRK.class);
        Long warehouseId = formData.getWarehouseId();
        List<ConsumeInventoryBatch> items = formData.getItems();
        for (ConsumeInventoryBatch item : items) {
            saveItem(item, warehouseId, applyNumber);
        }
    }

    @Override
    public void reject(String id) {
        FlowApply flowApply = flowApplyMapper.selectById(id);
        flowApply.setUpdateTime(LocalDateTime.now());
        flowApply.setState(ApplyStateEnum.REJECT.getValue());
        flowApplyMapper.updateById(flowApply);
    }

}
